package com.dengqi.mymodule.activity.loader.album;

import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dengqi.mymodule.R;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.RecyclerView;

/**
 * Created by dell on 2019/5/7
 */
public class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.AlbumViewHolder> {

    private List<Map<String, String>> datas = new ArrayList<>();

    public AlbumAdapter(Cursor cursor) {
        initData(cursor);
    }

    private void initData(Cursor mCursor) {
        if (mCursor != null && mCursor.moveToFirst()) {
            do {
                Map<String, String> maps = new LinkedHashMap<>();
                String albumCoverPath = mCursor.getString(mCursor.getColumnIndex("_data"));
                String albumName = mCursor.getString(mCursor.getColumnIndex("bucket_display_name"));
                String amount = mCursor.getString(mCursor.getColumnIndex("count"));
                maps.put("albumCoverPath", albumCoverPath);
                maps.put("albumName", albumName);
                maps.put("amount", amount);
                datas.add(maps);
            } while (mCursor.moveToNext());
        }
    }

    @Override
    public AlbumViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_album, null);
        return new AlbumViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AlbumViewHolder holder, int position) {
        String albumCoverPath = datas.get(position).get("albumCoverPath");
        String albumName = datas.get(position).get("albumName");
        String amount = datas.get(position).get("amount");

        holder.tvAlbumName.setText(albumName);
        holder.tvAlbumAmount.setText(amount);
        Glide.with(holder.ivAlbum.getContext())
                .load(albumCoverPath)
                .into(holder.ivAlbum);
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public static class AlbumViewHolder extends RecyclerView.ViewHolder {

        private ImageView ivAlbum;
        private TextView tvAlbumName;
        private TextView tvAlbumAmount;

        public AlbumViewHolder(View itemView) {
            super(itemView);
            ivAlbum = (ImageView) itemView.findViewById(R.id.album_iv_album);
            tvAlbumName = (TextView) itemView.findViewById(R.id.album_tv_album_name);
            tvAlbumAmount = (TextView) itemView.findViewById(R.id.album_tv_amount);
        }
    }
}